package com.example.blog_system_ssm.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service
public class MailService {
    // 发件人姓名
    @Value("${spring.mail.username}")
    private String mailUserName;

    // 发邮件的对象
    @Resource
    private JavaMailSender javaMailSender;

    // 发送的邮件模板页面
    @Resource
    private TemplateEngine templateEngine;

    // 激活账号邮件发送, activationUrl 账号激活 url 链接 , email 收件人邮箱
    public void sendMailForActivationAccount(String activationCode, String email){
        // 1) 创建邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            // 2) 设置邮件主题
            mimeMessageHelper.setSubject("欢迎来到BLOG -- 个人账号激活");
            // 3) 设置邮件发送
            mimeMessageHelper.setFrom(mailUserName);
            // 4) 设置邮件接收者,可多个
            mimeMessageHelper.setTo(email);
            // 5) 设置邮件抄送人,可多个
            // mimeMessageHelper.setCc();
            // 6) 设置隐私抄送人,可多个
            // mimeMessageHelper.setBcc();
            // 7) 创建邮件发送日期
            mimeMessageHelper.setSentDate(new Date());
            // 8) 设置上下文环境
            Context context = new Context();
            context.setVariable("activationCode",activationCode);
            // 加载模板
            String text = templateEngine.process("activation-account.html",context);
            // 9) 设置邮件的正文
            mimeMessageHelper.setText(text,true);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        // 9) 邮件发送
        javaMailSender.send(mimeMessage);
    }



}
